package com.homepage.web.rest;

import com.homepage.repository.HeadlineRepository;
import com.homepage.service.HeadlineService;
import com.homepage.service.dto.HeadlineDTO;
import com.homepage.util.HeaderUtil;
import com.homepage.util.ResponseUtil;
import com.homepage.web.rest.errors.BadRequestAlertException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import javax.validation.constraints.NotNull;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.List;
import java.util.Objects;
import java.util.Optional;


/**
 * REST controller for managing {@link com.homepage.domain.Headline}.
 */
@RestController
@RequestMapping("/company")
public class HeadlineResource {

    private final Logger log = LoggerFactory.getLogger(HeadlineResource.class);

    private static final String ENTITY_NAME = "headline";

    @Value("${common.clientApp.name}")
    private String applicationName;

    private final HeadlineService headlineService;

    private final HeadlineRepository headlineRepository;

    public HeadlineResource(HeadlineService headlineService, HeadlineRepository headlineRepository) {
        this.headlineService = headlineService;
        this.headlineRepository = headlineRepository;
    }

    /**
     * {@code POST  /headlines} : Create a new headline.
     *
     * @param headlineDTOS the headlineDTO to create.
     * @return the {@link ResponseEntity} with status {@code 201 (Created)} and with body the new headlineDTO, or with status {@code 400 (Bad Request)} if the headline has already an ID.
     * @throws URISyntaxException if the Location URI syntax is incorrect.
     */
    @PostMapping("/{companyName}/headlines")
    public ResponseEntity<List<HeadlineDTO>> createHeadline(@Valid @RequestBody List<HeadlineDTO> headlineDTOS,
                                                      @PathVariable String companyName) throws URISyntaxException {
        for(HeadlineDTO headlineDTO : headlineDTOS)
        {
            headlineDTO.setCompanyId(companyName);
        }

        log.debug("REST request to save Headline : {}", headlineDTOS);

        List<HeadlineDTO> result = headlineService.saveAll(headlineDTOS);
        return ResponseEntity
            .created(new URI("/company/"+companyName+"headlines"))
            .headers(HeaderUtil.createEntityCreationAlert(applicationName, true, ENTITY_NAME, "BATCH WAY"))
            .body(result);
    }

    @GetMapping("/{companyName}/headlines")
    public List<HeadlineDTO> getHeadlineByCompanyName(@PathVariable String companyName) {
       return headlineService.findAllByCompanyId(companyName);
    }

    /**
     * {@code PUT  /headlines/:id} : Updates an existing headline.
     *
     * @param id the id of the headlineDTO to save.
     * @param headlineDTO the headlineDTO to update.
     * @return the {@link ResponseEntity} with status {@code 200 (OK)} and with body the updated headlineDTO,
     * or with status {@code 400 (Bad Request)} if the headlineDTO is not valid,
     * or with status {@code 500 (Internal Server Error)} if the headlineDTO couldn't be updated.
     * @throws URISyntaxException if the Location URI syntax is incorrect.
     */
    @PutMapping("/headlines/{id}")
    public ResponseEntity<HeadlineDTO> updateHeadline(
        @PathVariable(value = "id", required = false) final Long id,
        @Valid @RequestBody HeadlineDTO headlineDTO
    ) throws URISyntaxException {
        log.debug("REST request to update Headline : {}, {}", id, headlineDTO);
        if (headlineDTO.getId() == null) {
            throw new BadRequestAlertException("Invalid id", ENTITY_NAME, "idnull");
        }
        if (!Objects.equals(id, headlineDTO.getId())) {
            throw new BadRequestAlertException("Invalid ID", ENTITY_NAME, "idinvalid");
        }

        if (!headlineRepository.existsById(id)) {
            throw new BadRequestAlertException("Entity not found", ENTITY_NAME, "idnotfound");
        }

        HeadlineDTO result = headlineService.save(headlineDTO);
        return ResponseEntity
            .ok()
            .headers(HeaderUtil.createEntityUpdateAlert(applicationName, true, ENTITY_NAME, headlineDTO.getId().toString()))
            .body(result);
    }

    /**
     * {@code PATCH  /headlines/:id} : Partial updates given fields of an existing headline, field will ignore if it is null
     *
     * @param id the id of the headlineDTO to save.
     * @param headlineDTO the headlineDTO to update.
     * @return the {@link ResponseEntity} with status {@code 200 (OK)} and with body the updated headlineDTO,
     * or with status {@code 400 (Bad Request)} if the headlineDTO is not valid,
     * or with status {@code 404 (Not Found)} if the headlineDTO is not found,
     * or with status {@code 500 (Internal Server Error)} if the headlineDTO couldn't be updated.
     * @throws URISyntaxException if the Location URI syntax is incorrect.
     */
    @PatchMapping(value = "/headlines/{id}", consumes = { "application/json", "application/merge-patch+json" })
    public ResponseEntity<HeadlineDTO> partialUpdateHeadline(
        @PathVariable(value = "id", required = false) final Long id,
        @NotNull @RequestBody HeadlineDTO headlineDTO
    ) throws URISyntaxException {
        log.debug("REST request to partial update Headline partially : {}, {}", id, headlineDTO);
        if (headlineDTO.getId() == null) {
            throw new BadRequestAlertException("Invalid id", ENTITY_NAME, "idnull");
        }
        if (!Objects.equals(id, headlineDTO.getId())) {
            throw new BadRequestAlertException("Invalid ID", ENTITY_NAME, "idinvalid");
        }

        if (!headlineRepository.existsById(id)) {
            throw new BadRequestAlertException("Entity not found", ENTITY_NAME, "idnotfound");
        }

        Optional<HeadlineDTO> result = headlineService.partialUpdate(headlineDTO);

        return ResponseUtil.wrapOrNotFound(
            result,
            HeaderUtil.createEntityUpdateAlert(applicationName, true, ENTITY_NAME, headlineDTO.getId().toString())
        );
    }

    /**
     * {@code GET  /headlines} : get all the headlines.
     *
     * @param filter the filter of the request.
     * @return the {@link ResponseEntity} with status {@code 200 (OK)} and the list of headlines in body.
     */
    @GetMapping("/headlines")
    public List<HeadlineDTO> getAllHeadlines(@RequestParam(required = false) String filter) {
        if ("headlineimage-is-null".equals(filter)) {
            log.debug("REST request to get all Headlines where headlineImage is null");
            return headlineService.findAllWhereHeadlineImageIsNull();
        }
        log.debug("REST request to get all Headlines");
        return headlineService.findAll();
    }

    /**
     * {@code GET  /headlines/:id} : get the "id" headline.
     *
     * @param id the id of the headlineDTO to retrieve.
     * @return the {@link ResponseEntity} with status {@code 200 (OK)} and with body the headlineDTO, or with status {@code 404 (Not Found)}.
     */
    @GetMapping("/headlines/{id}")
    public ResponseEntity<HeadlineDTO> getHeadline(@PathVariable Long id) {
        log.debug("REST request to get Headline : {}", id);
        Optional<HeadlineDTO> headlineDTO = headlineService.findOne(id);
        return ResponseUtil.wrapOrNotFound(headlineDTO);
    }

    /**
     * {@code DELETE  /headlines/:id} : delete the "id" headline.
     *
     * @param id the id of the headlineDTO to delete.
     * @return the {@link ResponseEntity} with status {@code 204 (NO_CONTENT)}.
     */
    @DeleteMapping("/headlines/{id}")
    public ResponseEntity<Void> deleteHeadline(@PathVariable Long id) {
        log.debug("REST request to delete Headline : {}", id);
        headlineService.delete(id);
        return ResponseEntity
            .noContent()
            .headers(HeaderUtil.createEntityDeletionAlert(applicationName, true, ENTITY_NAME, id.toString()))
            .build();
    }
}
